import {
    api,
} from '@/lib/api';
import {
    url,
} from '@/lib/utils';
import Vue from 'vue';

import { Module } from 'vuex';
import { RootState } from '@/types/store';

export interface PartnerState {
    searchNameList:ListWrap<Team.seachNameLst> & ListReq;
    /** 数据统计 */
    teamStatistics: Team.Stat | null;
    userInvitedList: (ListWrap<Team.Rebate> & ListReq & ListTotal) | null;
    /** 账户信息 */
    accountMap: {
        [userId: number]: number;
    };
    /** 队伍数据 */
    rebateDetailMap: {
        [userId: number]: User.Team;
    };
    /** 团队订单信息 */
    teamOrderList: ListWrap<Team.Order> & ListReq;
    rankListMap: any;
    /** 团队成员排行 */
    teamRankListMap: {
        [interval_type: string]: ListWrap<Team.LowerRank> & ListReq;
    };
    recommendOrderList: ListWrap<Order.Recommend> & ListReq;
}

const m: Module<PartnerState, RootState> = {
    namespaced: true,
    state: {
        searchNameList:null,
        teamStatistics: null,
        userInvitedList: null,
        accountMap: {},
        rebateDetailMap: {},
        teamOrderList: {
            list: [],
            loaded: false,
            req: false,
        },
        rankListMap: {},
        teamRankListMap: {},
        recommendOrderList: {
            list: [],
            loaded: false,
            req: false,
        },
    },
    mutations: {
        // 搜索门店
        setSearchMendian(state, data){
            state.searchNameList = data;
        },
        /**
         * 记录团队信息
         */
        setTeamStatistics(state, statistics) {
            state.teamStatistics = statistics;
        },
        /**
         * 初始化我的邀请列表
         */
        initUserInvitedList(state) {
            state.userInvitedList = {
                total: 0,
                list: [],
                loaded: false,
                req: false,
            };
        },
        concatUserInvitedList(state, { total, list }) {
            state.userInvitedList.total = total;
            state.userInvitedList.list.push(...list);
        },
        setUserInvitedListLoaded(state, { loaded }) {
            state.userInvitedList.loaded = loaded;
        },
        setUserInvitedListReq(state, { req }) {
            state.userInvitedList.req = req;
        },
        /**
         * 初始化订单列表
         */
        initTeamOrderList(state) {
            state.teamOrderList = {
                list: [],
                loaded: false,
                req: false,
            };
        },
        /**
         * 记录订单列表
         */
        concatTeamOrderList(state, { list }) {
            state.teamOrderList.list.push(...list);
        },
        /**
         * 订单列表是否全部加载
         */
        setTeamOrderListLoaded(state, { loaded }) {
            state.teamOrderList.loaded = loaded;
        },
        /**
         * 订单列表是否在请求
         */
        setTeamOrderListReq(state, { req }) {
            state.teamOrderList.req = req;
        },
        /**
         * 初始化推荐订单列表
         */
        initRecommendOrderList(state) {
            state.recommendOrderList = {
                list: [],
                loaded: false,
                req: false,
            };
        },
        /**
         * 记录推荐订单列表
         */
        concatRecommendOrderList(state, { list }) {
            state.recommendOrderList.list.push(...list);
        },
        /**
         * 推荐订单列表是否全部加载
         */
        setRecommendOrderListLoaded(state, { loaded }) {
            state.recommendOrderList.loaded = loaded;
        },
        /**
         * 推荐订单列表是否在请求
         */
        setRecommendOrderListReq(state, { req }) {
            state.recommendOrderList.req = req;
        },
        /**
         * 记录账户信息
         */
        setAccount(state, { id, account }) {
            Vue.set(state.accountMap, id, account);
        },
        setRebateDetail(state, { id, detail }) {
            Vue.set(state.rebateDetailMap, id, detail);
        },
        initRankList(state, { key }) {
            Vue.set(state.rankListMap, key, {
                self: null,
                rank: [],
                loaded: false,
                req: false,
            });
        },
        concatRankList(state, { key, data }) {
            Vue.set(state.rankListMap[key], 'self', data.self);
            if (data.rank) {
                state.rankListMap[key].rank.push(...(data.rank));
            }
        },
        setRankListLoaded(state, { key, loaded }) {
            state.rankListMap[key].loaded = loaded;
        },
        setRankListReq(state, { key, req }) {
            state.rankListMap[key].req = req;
        },
        initTeamRankList(state, { key }) {
            Vue.set(state.teamRankListMap, key, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        concatTeamRankList(state, { key, data }) {
            state.teamRankListMap[key].list.push(...data);
        },
        setTeamRankListLoaded(state, { key, loaded }) {
            state.teamRankListMap[key].loaded = loaded;
        },
        setTeamRankListReq(state, { key, req }) {
            state.teamRankListMap[key].req = req;
        },
    },

    actions: {
        async partnerApply(context, { code, name, idNumber, address, company, job, image, idCardPositive, idCardBack }) {
            // console.log('right 1');
            const res = await api.get({
                url: `${url}/api/user/apply_partner`,
                data: {
                    code,
                    name,
                    id_number: idNumber,
                    address,
                    company,
                    job,
                    image,
                    id_card_positive: idCardPositive,
                    id_card_back: idCardBack,
                },
            });
            return res;
        },
        /**
         * 获取团队数据统计
         */
        async getTeamStatistics({ commit }) {
            const res = await api.get({
                url: `${url}/api/team/statistics`,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setTeamStatistics', res.data.data);
            }
            return res;
        },
        /**
         * 获取我的邀请列表
         */
        async getUserInvitedList({ state, commit }, { offset, count, name, forceUpdate }) {
            if (!state.userInvitedList || forceUpdate) {
                commit('initUserInvitedList');
            }
            const wrap = state.userInvitedList;
            if (wrap.loaded || wrap.req) {
                return;
            }
            const end = offset + count;
            const length = wrap.list.length;
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - offset;
            }
            commit('setUserInvitedListReq', { req: true });
            const res = await api.get({
                url: `${url}/api/team/rebate`,
                data: {
                    offset,
                    count,
                    name: name || null,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const data = res.data.data;
                commit('concatUserInvitedList', {
                    total: data.total,
                    list: data.data,
                });
                // console.log('endndn');
                if (data.data && data.data.length < count) {
                    commit('setUserInvitedListLoaded', { loaded: true });
                }
            }
            commit('setUserInvitedListReq', { req: false });
            return res;
        },
        /**
         * 获取订单列表
         */
        async getTeamOrderList({ state, commit }, { offset, count, forceUpdate }) {
            if (!state.teamOrderList || forceUpdate) {
                commit('initTeamOrderList');
            }
            const wrap = state.teamOrderList;
            if (wrap.loaded || wrap.req) {
                return;
            }
            const end = offset + count;
            const length = wrap.list.length;
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - offset;
            }
            commit('setTeamOrderListReq', { req: true });
            const res = await api.get({
                url: `${url}/api/team/order`,
                data: {
                    offset,
                    count,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatTeamOrderList', {
                    list,
                });
                if (list.length < count) {
                    commit('setTeamOrderListLoaded', { loaded: true });
                }
            }
            commit('setTeamOrderListReq', { req: false });
            return res;
        },
        /**
         * 获取推荐订单列表
         */
        async getRecommendOrderList({ state, commit }, { type, time, search, userId, offset, count, forceUpdate }) {
            if (!state.teamOrderList || forceUpdate) {
                commit('initRecommendOrderList');
            }
            const wrap = state.recommendOrderList;
            if (wrap.loaded || wrap.req) {
                return;
            }
            const end = offset + count;
            const length = wrap.list.length;
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - offset;
            }
            commit('setRecommendOrderListReq', { req: true });
            const res = await api.get({
                url: `${url}/api/order/recommend`,
                data: {
                    type,
                    time,
                    search,
                    user_id: userId,
                    offset,
                    count,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatRecommendOrderList', {
                    list,
                });
                if (list.length < count) {
                    commit('setRecommendOrderListLoaded', { loaded: true });
                }
            }
            commit('setRecommendOrderListReq', { req: false });
            return res;
        },
        /**
         * 获得账户信息
         */
        async getAccount(context, { id }) {
            const res = await api.get({
                url: `${url}/api/user/account`,
                data: {
                    id,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                context.commit('setAccount', {
                    id,
                    account: res.data.data,
                });
            }
            return res;
        },
        async getRebateDetail(context, { id }) {
            const res = await api.get({
                url: `${url}/api/user/team`,
                data: {
                    id,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                context.commit('setRebateDetail', {
                    id,
                    detail: res.data.data,
                });
            }
            return res;
        },
        // 搜索门店
        async getSearchNamem({ commit }, { searchName }){
            const res = await api.get({
                url: `${url}/api/team/search_shop`,
                data: {
                    name:searchName,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setSearchMendian', res.data.data);
            }
            return res;
        },
        async getRankList({ state, commit }, { offset, count, levelName, interval, type, shop_name,year, forceUpdate }) {
            const key = `${interval}_${type}`;
            // console.log('key', key);
            let wrap = state.rankListMap[key];
            if (!wrap || forceUpdate) {
                commit('initRankList', { key });
                wrap = state.rankListMap[key];
            }
            // console.log(wrap, wrap.loaded, wrap.req);
            if (wrap.loaded || wrap.req) {
                return;
            }
            const listEnd = offset + count;
            const length = wrap.rank.length;
            if (listEnd <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = listEnd - offset;
            }
            commit('setRankListReq', { key, req: true });
            const data = {
                offset,
                count,
                type,
                interval,
                shop_name,
                year
            };
            const res = await api.get({
                url: `${url}/api/team/` + (levelName === 'partner' ? 'partner_rank' : 'rank'),
                data,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const data = res.data.data;
                commit('concatRankList', {
                    key,
                    data,
                });
                if (data.rank && data.rank.length < count) {
                    commit('setRankListLoaded', {
                        key,
                        loaded: true,
                    });
                }
            }
            commit('setRankListReq', { key, req: false });
            return res;
        },
        async getTeamRankList({ state, commit }, { offset, count, interval, type, forceUpdate }) {
            const key = `${interval}_${type}`;
            // console.log('key', key);
            let wrap = state.teamRankListMap[key];
            if (!wrap || forceUpdate) {
                commit('initTeamRankList', { key });
                wrap = state.teamRankListMap[key];
            }
            // console.log(wrap, wrap.loaded, wrap.req);
            if (wrap.loaded || wrap.req) {
                return;
            }
            const listEnd = offset + count;
            const length = wrap.list.length;
            if (listEnd <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = listEnd - offset;
            }
            commit('setTeamRankListReq', { key, req: true });
            const data = {
                offset,
                count,
                type,
                interval,
            };
            const res = await api.get({
                url: `${url}/api/team/lower_rank`,
                data,
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const data = res.data.data;
                commit('concatTeamRankList', {
                    key,
                    data,
                });
                if (data && data.length < count) {
                    commit('setTeamRankListLoaded', {
                        key,
                        loaded: true,
                    });
                }
            }
            commit('setTeamRankListReq', { key, req: false });
            return res;
        },
    },
};

export default m;
